﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI.Skins;
using Telerik.Web.UI;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.EnterpriseService;
using RN.ERP.Web.BasicService;

namespace RN.ERP.Web.CA
{
    public partial class CACorpRegAudit : BasePage
    {
        bool isInFlow = true;
        EnterpriseServiceClient enterpriseClient = new EnterpriseServiceClient();
        BasicServiceClient basicServiceClient = new BasicServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (AppID != "101")
                {
                    InitData();
                }
                BindFlowCode();
                BindCorpType();
            }
            else
            {
                InitData();
            }
            
        }

        private void InitData()
        {
            string classid = "25011";
            string msg = string.Empty;
            int controStatus = basicServiceClient.CheckCreater(out msg, "06", FlowClassId, UserInfo.RoleId);
;
            switch (controStatus)
            {
                case 0:
                    isInFlow = false;
                    if (FlowClassId == "-1" || FlowClassId == "" || FlowClassId == "0")
                    {
                        classid = "25011";
                        FlowClassId = "25011";
                    }
                    break;
                case 1:
                    classid = FlowClassId;
                    break;
                case 2:
                    classid = FlowClassId;
                    if (FlowClassId == "-1" || FlowClassId == "" || FlowClassId == "0")
                    {
                        classid = "25011";
                        FlowClassId = "25011";
                    }
                    break;
                default:
                    break;
            }
        }

        protected void ListCorps_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            var queryCondition = hdnCondition.Value;
            if (string.IsNullOrEmpty(queryCondition))
            {
                queryCondition = GetCondition();
            }
            int pageSize = ListCorps.PageSize;
            int pageIndex = ListCorps.CurrentPageIndex + 1;
            int count = 0;
            string queryClassid = "-1";
            if ( !string.IsNullOrEmpty(Request.QueryString["classid"]) )
            {
                queryClassid = Request.QueryString["classid"].ToString();
            }
            string corps = string.Empty;
            if (AppID == "101")
            {
                corps = enterpriseClient.GetCorpRegListLC(out count, pageIndex, pageSize, queryCondition, "14");
            }
            else
            {
                corps = enterpriseClient.GetCorpRegListYT(out count, pageIndex, pageSize, queryCondition, "06", queryClassid, UserInfo.RoleId);
            }
            var listNews = JsonConvert.DeserializeObject<IList<CompanyInfo>>(corps).ToList();
            int cnt = count;
            ListCorps.VirtualItemCount = cnt;
            ListCorps.DataSource = listNews;
        }

        //获取查询条件
        private string GetCondition()
        {
            List<string> listFlow = GetFlowCodes();
            List<QueryCompanyInfoCondition> queryList = new List<QueryCompanyInfoCondition>();
            foreach (var f in listFlow)
            {
                QueryCompanyInfoCondition condition = new QueryCompanyInfoCondition();
                string title = txtTitle.Text.Trim();
                string corpRole = ddlut.SelectedValue;
                if (!string.IsNullOrEmpty(title))
                {
                    condition.CorpName = new ParameterValue<string>() { O = OptEnum.Like, V = title };
                }
                if (!string.IsNullOrEmpty(corpRole))
                {
                    int cr = int.Parse(corpRole);
                    condition.RoleId = new ParameterValue<int?>() { O = OptEnum.Equal, V = cr };
                }
                if (f == "1,")
                {
                    condition.FlowCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = f };
                }
                else if(!string.IsNullOrEmpty(f))
                {
                    condition.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = f };
                }
                queryList.Add(condition);
            }
            return JsonConvert.SerializeObject(queryList);
        }
        

        private string AuditCorpReg(string data, string opt, string flowcode, string itemClassid, string content)
        {
            //List<string> list = new List<string>();
            //if (!string.IsNullOrEmpty(data))
            //{
            //    list.Add(data);
            //}
            string currentAreaCode = UserInfo.CurrentArea;
            User_Log log = new User_Log();
            log.IsrtDate = DateTime.Now;
            log.IsrtUser = UserInfo.CorpUserGuid;
            log.IsrtUserName = UserInfo.Name;
            log.IsrtUserArea = currentAreaCode;
            log.IsrtUserRole = UserInfo.RoleId;
            log.FunctionId = opt;
            log.Content = content;
            log.Notice = hdnComments.Value;
            var result = enterpriseClient.CorpRegAudit(data, currentAreaCode, JsonConvert.SerializeObject(log), flowcode, log.Notice, false, itemClassid);

           // var result = enterpriseClient.CorpRegAudit(JsonConvert.SerializeObject(list), currentAreaCode, JsonConvert.SerializeObject(log), flowcode, log.Notice, false, itemClassid);
            return result;
        }

        private List<string> GetFlowCodes()
        {
            List<string> listFlow = new List<string>();
            if (ddlStatus.Items.Count > 0 && ddlStatus.SelectedItem.Text == "处理中")
            {
                string flowCode = ddlStatus.SelectedValue.TrimEnd('@');
                foreach (var f in flowCode.Split('@'))
                {
                    if (!string.IsNullOrEmpty(f))
                    {
                        listFlow.Add(f);
                    }
                }
            }
            else
            {
                if (ddlStatus.SelectedValue.StartsWith("1,"))
                {
                    listFlow.Add("1,");
                }
                else
                {
                    listFlow.Add(ddlStatus.SelectedValue);
                }
            }
            return listFlow;
        }

        protected string GetAddress(string code)
        {
            string ret = string.Empty;
            try
            {
                ret = basicServiceClient.GetAddress(code);
                return ret;
            }
            catch (Exception ex)
            {
                return ret;
            }
        }


        private void BindFlowCode()
        {
            try
            {
                Dictionary<string, string> list = new Dictionary<string, string>();
                string msg = string.Empty;
                string areaCode = "06";
                if (AppID == "101")
                {
                    areaCode = "14";
                }
                if (isInFlow)
                    list = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetAllBusinessStatusAndProcessing(out msg, UserInfo.RoleId, areaCode, FlowClassId, false));
                else
                {
                        list = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetAllBusinessStatus(out msg, areaCode, FlowClassId));
                }

                ddlStatus.DataTextField = "Value";
                ddlStatus.DataValueField = "Key";
                ddlStatus.DataSource = list;
                ddlStatus.DataBind();
                ddlStatus.SelectedItem.Text = "处理中";

                ddlStatus.Items.Insert(0, new ListItem("全部", ""));

            }
            catch (Exception ex)
            {
            }
        }

        private void BindCorpType()
        {
            try
            {
                //25011--209--施工  25021--206--监理 73301--211--市政
                Dictionary<string, string> list = new Dictionary<string, string>();
                Dictionary<string, string> newList = new Dictionary<string, string>();
                list = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetDictionary("CorpUserType", "", ""));
                string corpRoleSG = "15";
                string corpRoleJL = "42,105,46,47,48,30,45";
                string corpRoleSZ = "7330";

                if (UserInfo.RoleId=="209")
                {
                    foreach (var item in list)
                    {
                        if (corpRoleSG == item.Key)
                        {
                            newList.Add(item.Key, item.Value);
                        }
                    }
                }else
                    if (UserInfo.RoleId=="206")
                    {
                       foreach (var item in list)
                        {
                            if (corpRoleJL.Contains(item.Key))
                            {
                                newList.Add(item.Key, item.Value);
                            }
                        } 
                    }
                    else
                        if (UserInfo.RoleId == "211")
                        {
                            foreach (var item in list)
                            {
                                if (corpRoleSZ == item.Key)
                                {
                                    newList.Add(item.Key, item.Value);
                                }
                            }
                        }
                        else
                        {
                            ddlut.Visible = false;
                        }

                ddlut.DataTextField = "Value";
                ddlut.DataValueField = "Key";
                ddlut.DataSource = newList;
                ddlut.DataBind();
                ddlut.Items.Insert(0, new ListItem("全部", ""));

            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 客户端grid刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            switch (e.Argument)
            {
                case"Rebind":
                ListCorps.MasterTableView.SortExpressions.Clear();
                ListCorps.MasterTableView.GroupByExpressions.Clear();
                ListCorps.Rebind();
                break;
                case"Audit":
                try
                {
                    int checkCount = 0;
                    string flowcode = string.Empty;
                    string strGuid = string.Empty;
                    string comments = hdnComments.Value;
                    string itemClassid = string.Empty;
                    foreach (GridDataItem dataItem in ListCorps.MasterTableView.Items)
                    {
                        if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                        {
                            strGuid = dataItem.GetDataKeyValue("CorpUserGuid").ToString();
                            flowcode = dataItem["FlowCode"].Text;
                            itemClassid = dataItem["FlowCodeType"].Text;
                            checkCount++;
                            if (checkCount >= 2)
                            {
                                //只能选择一条数据
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('只能选择一条数据！');", true);
                                return;
                            }
                        }
                    }
                    if (checkCount == 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要审核的数据！');", true);
                    }
                    else if (checkCount == 1)
                    {
                        string ret = AuditCorpReg(strGuid, "5", flowcode,itemClassid, "企业CA申请审核");
                        OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                        if (result.Result == true)
                        {
                            ListCorps.Rebind();
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                    }

                }
                catch (Exception ex)
                {
                    hidSysError.Value = ex.Message;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                }
                break;
                case "Back":
                try
                {
                    int checkCount = 0;
                    string flowcode = string.Empty;
                    string strGuid = string.Empty;
                    string itemClassid = string.Empty;
                    foreach (GridDataItem dataItem in ListCorps.MasterTableView.Items)
                    {
                        if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                        {
                            strGuid = dataItem.GetDataKeyValue("CorpUserGuid").ToString();
                            flowcode = dataItem["FlowCode"].Text;
                            itemClassid = dataItem["FlowCodeType"].Text;
                            checkCount++;
                            if (checkCount >= 2)
                            {
                                //只能选择一条数据
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('只能选择一条数据！');", true);
                                return;
                            }
                        }
                    }
                    if (checkCount == 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要退回的数据！');", true);
                    }
                    else if (checkCount == 1)
                    {
                        string ret = AuditCorpReg(strGuid, "6", flowcode, itemClassid, "企业CA申请退回");
                        OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                        if (result.Result == true)
                        {
                            ListCorps.Rebind();
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    hidSysError.Value = ex.Message;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                }
                break;
                default:
                break;
            }
        }

        protected string GetCorpClassKind(string type)
        {
            string output = string.Empty;
            if (!String.IsNullOrEmpty(type))
            {
                Dictionary<string, string> CorpTypeDic = JsonConvert.DeserializeObject<Dictionary<string, string>>
                    (Application[ApplicationConstant.APPLICATION_CORPUSERTYPE].ToString());
                try
                {
                    output = CorpTypeDic[type];
                }
                catch
                {
                    output = "";
                }
            }
            return output;
        }

        /// <summary>
        /// 只显示N个字的方法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string StrCut(string str, int num)
        {
            string nstr = System.Text.RegularExpressions.Regex.Replace(str, @"<[^>]*>", "");
            nstr = nstr.Replace("&nbsp;<STRONG></STRONG>", "");
            if (nstr.Length >= num)
            {
                return nstr.Substring(0, num) + "...";
            }
            return nstr;
        }

        public override bool IsCheckPermission
        {
            get { return false; }
        }
    }
}